package com.suneee.store.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.StringUtil;
import com.suneee.core.error.ErrorUtils;
import com.suneee.refund.address.bean.RefundAddress;
import com.suneee.refund.util.ReflectUtil;
import com.suneee.resources.ProductError;
import com.suneee.store.service.IThirdPartyService;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.AddressResult;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.UpdateSkuPrice;
import com.taobao.api.request.ItemQuantityUpdateRequest;
import com.taobao.api.request.ItemsCustomGetRequest;
import com.taobao.api.request.LogisticsAddressAddRequest;
import com.taobao.api.request.LogisticsAddressModifyRequest;
import com.taobao.api.request.LogisticsAddressRemoveRequest;
import com.taobao.api.request.LogisticsAddressSearchRequest;
import com.taobao.api.request.LogisticsOfflineSendRequest;
import com.taobao.api.request.TmallItemPriceUpdateRequest;
import com.taobao.api.response.ItemQuantityUpdateResponse;
import com.taobao.api.response.ItemsCustomGetResponse;
import com.taobao.api.response.LogisticsAddressAddResponse;
import com.taobao.api.response.LogisticsAddressModifyResponse;
import com.taobao.api.response.LogisticsAddressRemoveResponse;
import com.taobao.api.response.LogisticsAddressSearchResponse;
import com.taobao.api.response.LogisticsOfflineSendResponse;
import com.taobao.api.response.TmallItemPriceUpdateResponse;

public class TmallClientImpl implements IThirdPartyService {
	
	
	private final Logger logger = LoggerFactory.getLogger(TmallClientImpl.class);

	// 更新价格
	@Override
	public boolean updateStorePrice(Map<String, String> publicParams, Map<String, String> bizParams) throws Exception {
		String url = publicParams.get("url");
		String appkey = publicParams.get("appKey");
		String secret = publicParams.get("secret");
		String sessionKey = publicParams.get("appSession");
		String itemId = bizParams.get("itemId");
		String minPrice = bizParams.get("minParice");
		String outerId = bizParams.get("outerId");
		String price = bizParams.get("price");
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		TmallItemPriceUpdateRequest req = new TmallItemPriceUpdateRequest();
		req.setItemId(Long.valueOf(itemId));
		req.setItemPrice(StringUtil.formatStr(minPrice));
		List<UpdateSkuPrice> list = new ArrayList<UpdateSkuPrice>();
		UpdateSkuPrice obj = new UpdateSkuPrice();
		list.add(obj);
		obj.setOuterId(String.valueOf(outerId));
		obj.setPrice(StringUtil.formatStr(price));
		req.setSkuPrices(list);
		TmallItemPriceUpdateResponse rsp = client.execute(req, sessionKey);
		logger.info("更新天猫价格执行结果:"+rsp.getBody());
		if (rsp.isSuccess()) {
			return true;
		} else {
//			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE,rsp.getSubMsg());
			return false;
		}
	}

	// 根据外部ID获取商品价格列表
	@Override
	public List<Float> getPriceList(Map<String, String> publicParams, Map<String, String> bizParams) throws Exception {
		String url = publicParams.get("url");
		String appkey = publicParams.get("appKey");
		String secret = publicParams.get("secret");
		String sessionKey = publicParams.get("appSession");
		String spuId = bizParams.get("spuId");
		String toUpdateOuterId = bizParams.get("outerId");
		float toUpdatePrice = Float.valueOf(bizParams.get("price"));
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemsCustomGetRequest req = new ItemsCustomGetRequest();
		req.setOuterId(spuId);
		req.setFields("num_iid,sku");
		ItemsCustomGetResponse rsp = client.execute(req, sessionKey);
		logger.info("根据外部ID获取商品列表:"+rsp.getBody());
		if (rsp.getItems() != null && !rsp.getItems().isEmpty()) {
			List<Item> items = rsp.getItems();
			List<Float> priceList = new ArrayList<>();
			for (int i = 0; i < items.size(); i++) {
				Item item = items.get(i);
				List<com.taobao.api.domain.Sku> skus = item.getSkus();
				for (int j = 0; j < skus.size(); j++) {
					com.taobao.api.domain.Sku sku = skus.get(j);
					String outerIdTmp = sku.getOuterId();
					//Long quantity = sku.getQuantity();
					float price = Float.valueOf(sku.getPrice());
//					if (quantity != 0) {
						if (outerIdTmp.equals(toUpdateOuterId)) {
							priceList.add(toUpdatePrice);
						} else {
							priceList.add(price);
						}
//					}
				}
			}
			return priceList;
		} else {
			return null;
		}

	}

	@Override
	public boolean updateStock(Map<String, String> publicParams, Map<String, String> bizParams) throws Exception {
		TaobaoClient client = new DefaultTaobaoClient(publicParams.get("url"), publicParams.get("appKey"),
				publicParams.get("secret"));
		ItemQuantityUpdateRequest req = new ItemQuantityUpdateRequest();
		req.setNumIid(Long.valueOf(bizParams.get("numIid")));
		req.setOuterId(bizParams.get("outerId"));
		req.setQuantity(Long.valueOf(bizParams.get("quantity")));
		req.setType(2L);
		ItemQuantityUpdateResponse rsp = client.execute(req, publicParams.get("appSession"));
		logger.info("更新库存:"+rsp.getBody());
		if (rsp.isSuccess()) {
			return true;
		} else {
//			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE,rsp.getSubMsg());
			return false;
		}
	}
	
	

	@Override
	public boolean updateOrderShoppStatus(Map<String, String> publicParams, Map<String, String> bizParams)
			throws Exception {
		String is_split = bizParams.get("is_split");
		String sub_tid = bizParams.get("subTid");
		TaobaoClient client = new DefaultTaobaoClient(publicParams.get("url"), publicParams.get("appKey"),
				publicParams.get("secret"));
		LogisticsOfflineSendRequest req = new LogisticsOfflineSendRequest();
		if (StringUtils.isNotEmpty(sub_tid)) {
			req.setSubTid(sub_tid);
		}

		req.setTid(Long.valueOf(bizParams.get("tid")));
		if (StringUtils.isNotEmpty(is_split)) {
			req.setIsSplit(Long.valueOf(is_split));
		}
		req.setOutSid(bizParams.get("outSid"));
		req.setCompanyCode(bizParams.get("companyCode"));
		LogisticsOfflineSendResponse rsp = client.execute(req, publicParams.get("appSession"));
		logger.info("更新交易发货状态:"+rsp.getBody());
		if (rsp.isSuccess() ||rsp.getSubCode().equals("CD06")) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 新增天猫退货地址 并返回新增退货地址对象集合
	 */
	@Override
	public List<RefundAddress> insertRefundAddressInfo(Map<String, String> publicParams, RefundAddress refundAddress)
	{
		//创建天猫接口连接对象
		TaobaoClient client = new DefaultTaobaoClient(publicParams.get("url"), publicParams.get("appKey"),publicParams.get("secret"));
		//创建天猫接口入参对象
		LogisticsAddressAddRequest req = new LogisticsAddressAddRequest();
		
		//获取企业名称
		String entName = ContextHelper.getCurrentLoginInfo().getEnterprise().getName();
		refundAddress.setCompany(entName);
		
		/*
		 * 设置入参值
		 */
		req.setContactName(refundAddress.getName());//"姓名"
		req.setProvince(refundAddress.getReceiverState());//"浙江省"
		req.setCity(refundAddress.getReceiverCity());//"杭州市"
		req.setCountry(refundAddress.getReceiverDistrict());//"西湖区"
		req.setAddr(refundAddress.getReceiverAddress());//"华星路xx号"
		req.setZipCode(refundAddress.getPostCode());//"315040"
		req.setMobilePhone(refundAddress.getPhone()); //136********"
		req.setMemo(refundAddress.getAddressRemark());//"备注"
		req.setSellerCompany(refundAddress.getCompany());//公司
		
		//判断是否设置改退货地址未默认
		if(refundAddress.getDefaults())
		{
			req.setCancelDef(true);
			req.setGetDef(true);
		}
		
		//调用天猫接口
		LogisticsAddressAddResponse rsp = null;
		try
		{
			rsp = client.execute(req, publicParams.get("appSession"));
		}
		catch (Exception e) 
		{
			logger.info("新增退货地址："+e.toString());
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"同步退货地址失败");
		}
		
		//判断接口是否调用成功
		if(null != rsp && rsp.isSuccess())
		{
			Map<String, String> bizParams = new HashMap<>();
			//若新增的地址是默认地址。 则只需要查询默认地址即可 否则查询所有的退货地址（目前 中台默认退货地址对应天猫的发货地址） 
			
			if(refundAddress.getDefaults())
			{
				bizParams.put("rdef", "cancel_def");
			}
			
			//新增退货地址以后。同时全量查询地址库地址并返回
			return queryRefundAddressInfo(publicParams, bizParams);
		}
		else
		{
			//调用失败 ：写入日志并返回错误信息至前端显示
			logger.info("更新交易发货状态:"+rsp.getBody());
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"同步退货地址失败");
		}
	}
	
	
	
	/**
	 * 修改天猫退货地址
	 */
	@Override
	public boolean updateRefundAddressInfo(Map<String, String> publicParams, RefundAddress rfdAddress)
	{
		String entName = ContextHelper.getCurrentLoginInfo().getEnterprise().getName();
		rfdAddress.setCompany(entName);
		//创建天猫接口连接对象
		TaobaoClient client = new DefaultTaobaoClient(publicParams.get("url"), publicParams.get("appKey"),publicParams.get("secret"));
		//创建天猫接口入参对象
		LogisticsAddressModifyRequest req = new LogisticsAddressModifyRequest();
		
		
		ReflectUtil.ztEPtoTmallAddress(rfdAddress, req);
		/*req.setContactId(rfdAddress.getId());
		req.setContactName(rfdAddress.getName());
		req.setProvince(rfdAddress.getReceiverState());
		req.setCity(rfdAddress.getReceiverCity());
		req.setCountry(rfdAddress.getReceiverDistrict());
		req.setAddr(rfdAddress.getReceiverAddress());
		req.setZipCode(rfdAddress.getPostCode());
		req.setMobilePhone(rfdAddress.getPhone());
		req.setSellerCompany(rfdAddress.getCompany());
		req.setMemo(rfdAddress.getAddressRemark());
		req.setCancelDef(rfdAddress.getDefaults());*/
		
		//掉用天猫接口
		LogisticsAddressModifyResponse rsp = null;
		try 
		{
			rsp = client.execute(req, publicParams.get("appSession"));
			if(null != rsp && rsp.isSuccess())
			{
				return true;
			}
			else
			{
				throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,rsp.getSubMsg());
			}
		}
		catch (Exception e) 
		{
			logger.info("更新退货地址信息:"+e.toString());
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"修改退货地址失败:" + rsp.getSubMsg());
		}
	}
	/**
	 * 查询天猫退货地址集合
	 */
	@Override
	public List<RefundAddress> queryRefundAddressInfo(Map<String, String> publicParams, Map<String, String> bizParams)
	{
		//返回结果集
		List<RefundAddress> adsList= new ArrayList<RefundAddress>();
		
		//创建天猫接口连接对象
		TaobaoClient client = new DefaultTaobaoClient(publicParams.get("url"), publicParams.get("appKey"),publicParams.get("secret"));
		//创建天猫接口入参对象
		LogisticsAddressSearchRequest req = new LogisticsAddressSearchRequest();
		
		/**
		 * 可选，参数列表如下：
		 * no_def:查询非默认地址
		 * get_def:查询默认取货地址，也即对应卖家后台地址库中发货地址（send_def暂不起作用）
		 * cancel_def:查询默认退货地址 缺省此参数时，查询所有当前用户的地址库
		 */
		//判断入参对象是否为空 若不为空 则查询 默认退货地址信息 反之则查询该企业下所有的退货地址信息
		if(null != bizParams && bizParams.size() > 0)
		{
			req.setRdef(bizParams.get("rdef"));
		}
		
		//调用天猫接口
		LogisticsAddressSearchResponse rsp;
		try 
		{
			rsp = client.execute(req, publicParams.get("appSession"));
			
			//判断接口是否调用成功且有返回实体退货地址对象 并将返回的退货地址对象转换成中台退货地址对象  并将其设置到adsList中
			if(null != rsp && rsp.isSuccess())
			{
				List<AddressResult> resultList =  rsp.getAddresses();
				if(null != resultList && resultList.size() > 0)
				{
					RefundAddress rfdAddress = null;
					for(AddressResult result:resultList)
					{
						rfdAddress = new RefundAddress();
						// 将天猫地址对象转换成中台地址对象
						ReflectUtil.tmallChangeAddress(result, rfdAddress);
						
						//转换成功 将对象设置到adsList 中
						if(null != rfdAddress.getId() && 0 != rfdAddress.getId())
						{
							adsList.add(rfdAddress);
						}
					}
				}
			}
			
		}
		catch (Exception e)
		{
			logger.info("查询退货地址信息:"+e.toString());
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"查询退货地址失败");
		}
		return adsList;
	}
	/**
	 * 删除天猫退货地址
	 */
	@Override
	public boolean deleteRefundAddressInfo(Map<String, String> publicParams, Map<String, String> bizParams)
	{
		//创建天猫接口连接对象
		TaobaoClient client = new DefaultTaobaoClient(publicParams.get("url"), publicParams.get("appKey"),publicParams.get("secret"));
		//创建天猫接口入参对象
		LogisticsAddressRemoveRequest req = new LogisticsAddressRemoveRequest();
		//设置入参值
		req.setContactId(Long.parseLong(bizParams.get("id")));
		
		//调用接口
		LogisticsAddressRemoveResponse rsp;
		try
		{
			rsp = client.execute(req, publicParams.get("appSession"));
			
			//判断是否调用成功
			if(null != rsp && rsp.isSuccess())
			{
				return true;
			}
			else
			{
				if("地址库信息不存在".equals(rsp.getSubMsg()))
				{
					return true;
				}
				else if("isv.logistics-address-service-error:B102".equals(rsp.getSubCode()))
				{
					throw ErrorUtils.wrap(ProductError.TMALL_HX_FAIL,"不能删除默认发货、取货、退货地址");
				}
			}
		}
		catch (ApiException e) 
		{
			logger.info("删除退款地址信息:"+e.toString());
			throw ErrorUtils.wrap(ProductError.TMALL_HX_FAIL,"调用删除退款地址报错");
		}
		catch (Exception e) {
			logger.info("删除退款地址信息:"+e.toString());
			throw ErrorUtils.wrap(ProductError.TMALL_HX_FAIL,"未知错误");
		}
		return false;
	}

}
